package com.supreme.threadserver.threadpkg;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class VolatileThread implements Runnable, ConsumerHandler<Boolean> {

    private Consumer<Boolean> threadConsumer;
    private Boolean stopThread = false;

    public VolatileThread() {
    }

    public VolatileThread(Consumer<Boolean> threadConsumer) {
        this.threadConsumer = threadConsumer;
    }

    public void setStopThread(Boolean stopThread) {
        this.stopThread = stopThread;
    }

    @Override
    public void run() {
        Thread thread = Thread.currentThread();
        while (true) {
            try {
                System.out.printf("THREAD = %s DATE = %s\n", thread.getName(), LocalDateTime.now());
                System.out.println("stopThread = " + stopThread);
                if (this.stopThread) {
                    break;
                }
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                break;
            }
        }

        System.out.printf("THREAD = %s FINISH\n", thread.getName());
        Optional.ofNullable(this.threadConsumer).ifPresent(consumer -> consumer.accept(true));
    }

    @Override
    public void setConsumer(Consumer<Boolean> consumer) {
        this.threadConsumer = consumer;
    }
}
